package de.mpii.web;

import java.io.File;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import de.mpii.Config;
import de.mpii.html.parser.Parser;
import de.mpii.util.Uio;

/**
 * 
 * 
 * @author nanmus
 * 
 */
public class Google implements SearchEngine {

	private static final String PATH = Config.BASE_PATH + "/google";

	public static void main(String[] args) throws Exception {
		SearchEngine google = new Google();

		google.search("list of artists");

	}

	@Override
	public List<URL> search(String keywords) throws Exception {
		List<URL> urls = new ArrayList<URL>();

		keywords = keywords.toLowerCase().replace(' ', '_');

		File dir = new File(PATH);
		Parser parser;
		String urlString, content;
		URI uri = null;

		for (File file : dir.listFiles()) {

			if (!file.isFile() || !file.getName().contains(keywords))
				continue;

			System.out.println(">> FOUND CACHE FILE " + file.getName());

			content = Uio.read(file);

			parser = new GoogleUrlParser(content);

			while ((urlString = parser.next()) != null) {
				try {
					uri = new URI(urlString);
				} catch (Exception e) {
					System.out.println(">> BAD URL: " + urlString);
					continue;
				}

				assert uri != null;
				urls.add(uri.toURL());
			}
		}

		return urls;
	}

}
